<?php

namespace Pm\Controllers;

use Admin\Models\pm\XhpmProjectTask;
use Helpers\Main;
use Helpers\Assets;
use Helpers\User;
use Admin\Models\pm\XhpmProject;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\pm\XhpmProjectMember;
use Admin\Models\pm\XhpmProjectLog;
use Admin\Models\pm\XhpmProjectCount;
use Admin\Models\pm\XhpmProduct;
use Admin\Models\track\XhtrackTask;
use Services\App;
use Modules\Power;
use Admin\Models\sys\XhsysEnum;


class ProjectController extends ControllerBase
{
    private static $project_status;

    private static $depTag;

    private static $productTypes = [
        1 => '学生',
        2 => '教师',
        3 => '家长',
        4 => '通用',
        5 => '服务端',
        6 => 'Web端',
    ];

    private static $bArchived = [
        0 => '未归档' ,
        1 => '已归档',
    ];

    public function initialize()
    {
        $userInfo = Main::getLoginUserInfo();
        $logonName = $userInfo['logonName'];
        if ($logonName == 'admin') {
            $dep = 'XHJSB';
        } elseif ($userInfo['depTag']) {
            if (in_array('XHJSB', $userInfo['depTag'])) {
                $dep = 'XHJSB';
            } else {
                $dep = $userInfo['depTag'][0];
            }
        } else {
            $dep = '';
        }
        self::$depTag = $dep;
        self::$project_status = $dep == 'XHJSB' ? [
            1 => '未开始',
            2 => '进行中',
            5 => '已完成',
            3 => '测试中',
            4 => '已发布',
            6 => '已暂停',
        ] : [
            1 => '未开始',
            2 => '进行中',
            5 => '已完成',
            6 => '已暂停',
        ];
    }

    /**
     * 注释
     *
     * create by zqk 19990909
     */
    public function homeAction()
    {
        $pids = $this->getProjectIds();
        $unStartProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=1 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();
        $doingProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=2 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();
        $testingProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=3 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();
        $publishedProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=4 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();
        $finishedProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=5 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();
        $pauseProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=6 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->limit(5)
            ->getQuery()
            ->execute()
            ->toArray();

        $this->view->pick('project/home');
        $this->view->setVars([
            'unStartProjs' => $unStartProjs,
            'doingProjs' => $doingProjs,
            'testingProjs' => $testingProjs,
            'publishedProjs' => $publishedProjs,
            'finishedProjs' => $finishedProjs,
            'pauseProjs' => $pauseProjs,
            'project_status' => self::$project_status,
        ]);
    }

    /**
     * 首页查看更多页面
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180620
     */
    public function homePageAction()
    {
        if (!Power::exist('Bpm_Project')) {
            return $this->sendViewError('无项目列表权限');
        }
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myMain.js');
        $pids = $this->getProjectIds();
        $unStartProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete = 0 AND iProjectStatus = 1 AND iParentPid = 0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($unStartProjs as $k => $unStartProj) {
            $pid = $unStartProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $unStartProjs[$k]['process'] = $process;
        }
        $doingProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete = 0 AND iProjectStatus = 2 AND iParentPid = 0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($doingProjs as $k => $doingProj) {
            $pid = $doingProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $doingProjs[$k]['process'] = $process;
        }
        $testingProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus = 3 AND iParentPid = 0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($testingProjs as $k => $testingProj) {
            $pid = $testingProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $testingProjs[$k]['process'] = $process;
        }
        $publishedProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus = 4 AND iParentPid = 0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($publishedProjs as $k => $publishedProj) {
            $pid = $publishedProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $publishedProjs[$k]['process'] = $process;
        }
        $finishedProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete = 0 AND iProjectStatus = 5 AND iParentPid = 0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($finishedProjs as $k => $finishedProj) {
            $pid = $finishedProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $finishedProjs[$k]['process'] = $process;
        }
        $pauseProjs = $this->modelsManager->createBuilder()
            ->addFrom('Admin\Models\pm\XhpmProject')
            ->where('bDelete=0 AND iProjectStatus=6 AND iParentPid=0')
            ->inwhere('iProjectId', $pids)
            ->orderBy("iProjectId desc")
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($pauseProjs as $k => $pauseProj) {
            $pid = $pauseProj['iProjectId'];
            $process = $this->getProjectProcess($pid);
            $pauseProjs[$k]['process'] = $process;
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        $this->view->pick('project/homePage');
        $this->view->setVars([
            'unStartProjs' => $unStartProjs,
            'doingProjs' => $doingProjs,
            'testingProjs' => $testingProjs,
            'publishedProjs' => $publishedProjs,
            'finishedProjs' => $finishedProjs,
            'pauseProjs' => $pauseProjs,
            'project_status' => self::$project_status,
        ]);
    }

    /**
     * 获取项目进度
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    private function getProjectProcess($projctId)
    {
        $cPid = XhpmProject::findFirst([
            'columns' => 'iProjectId,iProjectStatus',
            'conditions' => "iParentPid = $projctId AND bDelete = 0 AND iProjectGrade = 2",
            'order' => 'iProjectId DESC'
        ]);
        if ($cPid) {
            $visionCount = XhpmProjectCount::findFirst([
                'columns' => 'iSumTaskNum,iFinishedTaskNum,iProjectId',
                'conditions' => "iProjectId = $cPid->iProjectId AND bDelete = 0 ",
            ]);
            if ($visionCount->iSumTaskNum) {
                $floatNum = intval($visionCount->iFinishedTaskNum) / $visionCount->iSumTaskNum;
                $process = intval(sprintf("%.2f", $floatNum) * 100);
            } else {
                $process = 0;
            }
        } else {
            $count = XhpmProjectCount::findFirst([
                'columns' => 'iSumTaskNum,iFinishedTaskNum,iProjectId',
                'conditions' => "iProjectId = $projctId AND bDelete = 0 ",
            ]);
            if ($count->iSumTaskNum) {
                $floatNum = intval($count->iFinishedTaskNum) / $count->iSumTaskNum;
                $process = intval(sprintf("%.2f", $floatNum) * 100);
            } else {
                $process = 0;
            }
        }
        return $process;
    }

    /**
     * 项目列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function indexAction()
    {
        if (!Power::exist('Bpm_Project')) {
            return $this->sendViewError('无项目列表权限');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('project/projectList');
        Assets::importJs('js/project/projectList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'depTag' => self::$depTag,
            'projectStatus' => self::$project_status,
            'projectAdd' => Power::exist('Bpm_Project_Add'),
            'projectEdit' => Power::exist('Bpm_Project_Edit'),
            'projectDel' => Power::exist('Bpm_Project_Del'),
            'projectCheck' => Power::exist('Bpm_Project_Check'),
            'projectArchive' => Power::exist('Bpm_Project_Archive'),
            'alterProjectStatus' => Power::exist('Bpm_Project_ChangeStatus'),
            'projectTypes' => XhsysEnum::getEnumByNodeName('项目类型'),
            'bArchived' => self::$bArchived,
        ]);
    }

    /**
     * 获取项目列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180412
     */
    public function getProjectAction()
    {
        try {
            if (!Power::exist('Bpm_Project')) {
                return $this->sendErrorResponse(500, '无项目列表权限');
            }
            $pids = $this->getProjectIds();
            $status = $this->request->getPost('status', 'int'); //根据项目状态太筛选
            $bArchived = $this->request->getPost('bArchived', 'int'); //根据项目状态太筛选
            $projectName = $this->request->getPost('projectName', 'string'); //根据项目状态太筛选
            $condition = "p.bDelete=0 And p.iParentPid=0 AND p.iProjectGrade=1";
            $condition .= isset($bArchived)&&$bArchived != ''&&in_array($bArchived, [0,1]) ? " AND p.bArchived = $bArchived" : '';
            $condition .= $status ? " AND p.iProjectStatus = $status" : '';
            $condition .= $projectName ? " AND p.sProjectName  LIKE '%$projectName%'" : '';
            $builder = $this->modelsManager->createBuilder()
                ->columns("c.iSumTaskNum,c.iFinishedTaskNum,p.iProjectId,p.iProjectGrade,p.sProjectName,
                p.sProjectIntroduce,p.iProjectType,p.iParentPid,p.sProjectVersion,p.iProjectStatus,p.tCreateDate,
                p.tLastModifyDate")
                ->addFrom('Admin\Models\pm\XhpmProject', 'p')
                ->leftjoin('Admin\Models\pm\XhpmProjectCount', 'p.iProjectId = c.iProjectId', 'c')
                ->where($condition);
            if (!User::isAdmin()) {
                $builder ->inWhere("p.iProjectId", $pids);
            }
            $builder->orderBy("p.iProjectId desc");
            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $key => $value) {
                $iParentPid = $data['rows'][$key]['iProjectId'];
                $cPid = XhpmProject::findFirst([
                    'columns' => 'iProjectId,iProjectStatus',
                    'conditions' => "iParentPid = $iParentPid AND bDelete = 0 AND iProjectGrade = 2",
                    'order' => 'iProjectId DESC'
                ]);
                if ($cPid) {
                    $data['rows'][$key]['ifChangeStatus'] = 0;
                    $visionCount = XhpmProjectCount::findFirst([
                        'columns' => 'iSumTaskNum,iFinishedTaskNum,iProjectId',
                        'conditions' => "iProjectId = $cPid->iProjectId AND bDelete = 0 ",
                        'order' => 'iProjectId desc'
                    ]);
                    if ($visionCount->iSumTaskNum) {
                        $floatNum = intval($visionCount->iFinishedTaskNum) / $visionCount->iSumTaskNum;
                        $process = intval(sprintf("%.2f", $floatNum) * 100);
                        $data['rows'][$key]['iProcess'] = $process;
                    } else {
                        $data['rows'][$key]['iProcess'] = 0;
                    }
                    $data['rows'][$key]['iProjectStatus'] = $cPid->iProjectStatus;
                } else {
                    $data['rows'][$key]['ifChangeStatus'] = 1;
                    if ($data['rows'][$key]['iSumTaskNum']) {
                        $floatNum = intval($data['rows'][$key]['iFinishedTaskNum']) / $data['rows'][$key]['iSumTaskNum'];
                        $process = intval(sprintf("%.2f", $floatNum) * 100);
                        $data['rows'][$key]['iProcess'] = $process;
                    } else {
                        $data['rows'][$key]['iProcess'] = 0;
                    }
                }
                $data['rows'][$key]['iconCls'] = 'fa fa-file-text';
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 新建/编辑 项目表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function projectFormAction()
    {
        $depTag = self::$depTag;
        switch ($depTag) {
            case 'XHJSB'://开发
                $this->view->pick('project/xhjsbProjectForm');
                $projectType = 1;
                break;
            default:
                $this->view->pick('project/projectForm');
                $projectType = 2;
        }
        $iParentPid = $this->request->getQuery('iParentPid', 'int');
        $iProjectId = $this->request->getQuery('iProjectId', 'int');
        $iProjectGrade = $this->request->getQuery('iProjectGrade', 'int');
        if ($iProjectId) {
            if ($iProjectGrade == 1) {
                if (!Power::exist('Bpm_Project_Edit')) {
                    return $this->sendViewError('无编辑项目权限');
                }
            } elseif ($iProjectGrade == 2) {
                if (!Power::exist('Bpm_Project_Version_Edit')) {
                    return $this->sendViewError('无编辑项目版本权限');
                }
            } elseif ($iProjectGrade == 3) {
                if (!Power::exist('Bpm_Project_Module_Edit')) {
                    return $this->sendViewError('无编辑项目模块权限');
                }
            }
        } else {
            if ($iProjectGrade == 1) {
                if (!Power::exist('Bpm_Project_Add')) {
                    return $this->sendViewError('无新增项目权限');
                }
            } elseif ($iProjectGrade == 2) {
                if (!Power::exist('Bpm_Project_Version_Add')) {
                    return $this->sendViewError('无新增版本权限');
                }
            } elseif ($iProjectGrade == 3) {
                if (!Power::exist('Bpm_Project_Module_Add')) {
                    return $this->sendViewError('无新增模块权限');
                }
            }
        }
        Assets::easyUI();
        Assets::select2();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/project/projectForm.js');
        $this->view->setVars([
            'projectType' => $projectType,
            'iProjectId' => $iProjectId,
            'iProjectGrade' => $iProjectGrade,
            'iParentPid' => $iParentPid,
        ]);
    }

    /**
     * 新建/编辑项目/版本/模块
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function saveProjectAction()
    {
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        //项目创建人id  && name
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        $iProjectGrade = $this->request->getPost('iProjectGrade', 'int');//获取gradeid
        $iParentPid = $this->request->getPost('iParentPid', 'int');//获取parentId
        $sProjectName = $this->request->getPost('sProjectName');//名称
        $sProjectVersion = $this->request->getPost('sProjectVersion');//版本
        $if_power = $this->checkProjectPower($iProjectGrade, $iParentPid);
        if (!$if_power) {
            return $this->sendErrorResponse(400, '参数错误！');
        }
        try {
            $this->db->begin();  //开启事务
            $parent = '';
            if ($iProjectId) {
                if ($iProjectGrade == 1) {
                    if (!Power::exist('Bpm_Project_Edit')) {
                        return $this->sendErrorResponse(500, '权限不足', '无编辑项目权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "iProjectId != $iProjectId AND sProjectName = '" . $sProjectName . "' AND bDelete = 0 AND iProjectGrade = $iProjectGrade",
                    ]);
                } elseif ($iProjectGrade == 2) {
                    if (!Power::exist('Bpm_Project_Version_Edit')) {
                        return $this->sendErrorResponse(500, '权限不足', '无编辑版本权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "iProjectId != $iProjectId AND iParentPid = $iParentPid AND  sProjectVersion = '" . $sProjectVersion . "' AND bDelete = 0 AND iProjectGrade = $iProjectGrade",
                    ]);
                } elseif ($iProjectGrade == 3) {
                    if (!Power::exist('Bpm_Project_Module_Edit')) {
                        return $this->sendErrorResponse(500, '权限不足', '无编辑模块权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "iProjectId != $iProjectId AND iParentPid = $iParentPid AND sProjectName = '" . $sProjectName . "' AND bDelete = 0 AND iProjectGrade = $iProjectGrade",
                    ]);
                } else {
                    return $this->sendErrorResponse(500, '参数错误', '等级错误');
                }
                if ($projectInfo) {
                    return $iProjectGrade == 2 ?
                        $this->sendErrorResponse(400, "'$sProjectVersion'" . '已存在')
                        : $this->sendErrorResponse(400, "'$sProjectName'" . '已存在');
                }
                $project = XhpmProject::findFirst($iProjectId);
                if (!$project) {
                    return $this->sendErrorResponse(400, '操作项目不存在！');
                }
                $pids = $this->getProjectIds();

                if ((!in_array($iProjectId, $pids)) && !User::isAdmin()) {
                    return $this->sendErrorResponse(400, '无权操作该项目！');
                }
            } else {
                if ($iProjectGrade == 1) {
                    if (!Power::exist('Bpm_Project_Add')) {
                        return $this->sendErrorResponse(500, '权限不足', '无创建项目权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "sProjectName = '" . $sProjectName . "' AND bDelete = 0 AND iProjectGrade = $iProjectGrade",
                    ]);
                } elseif ($iProjectGrade == 2) {
                    if (!Power::exist('Bpm_Project_Version_Add')) {
                        return $this->sendErrorResponse(500, '权限不足', '无创建版本权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "sProjectVersion = '" . $sProjectVersion . "' AND iParentPid = $iParentPid AND bDelete = 0 AND iProjectGrade = $iProjectGrade",
                    ]);
                    $parent = XhpmProject::findFirst([
                        'columns' => 'iProductId',
                        'conditions' => "bDelete = 0 AND iProjectId = $iParentPid"
                    ]);
                } elseif ($iProjectGrade == 3) {
                    if (!Power::exist('Bpm_Project_Module_Add')) {
                        return $this->sendErrorResponse(500, '权限不足', '无创建模块权限');
                    }
                    $projectInfo = XhpmProject::findFirst([
                        'conditions' => "sProjectName = '" . $sProjectName . "' AND bDelete = 0 AND iParentPid = $iParentPid AND iProjectGrade = $iProjectGrade",
                    ]);
                    $parent = XhpmProject::findFirst([
                        'columns' => 'iProductId',
                        'conditions' => "bDelete = 0 AND iProjectId = $iParentPid"
                    ]);
                } else {
                    return $this->sendErrorResponse(500, '参数错误', '等级错误');
                }
                if ($projectInfo) {
                    return $iProjectGrade == 2 ? $this->sendErrorResponse(400, "'$sProjectVersion'" . '已存在')
                        : $this->sendErrorResponse(400, "'$sProjectName'" . '已存在');
                }
                $project = new XhpmProject();
                $project->iProjectStatus = 1;
            }
            $project->assign($this->request->getPost());
            if ($parent) {
                $project->iProductId = $parent->iProductId;
            }
            $result = $project->save();
            if (!$result) {
                $this->db->rollback();
                return $iProjectId ? $this->sendErrorResponse(500, '编辑失败') : $this->sendErrorResponse(500, '创建失败');
            }

            if ($iProjectId && $iProjectGrade == 1) {
                $productId = $project->iProductId;
                $pIds = $this->getPids($iProjectId, $iProjectGrade);
                if ($pIds) {
                    $re = $this->modelsManager->executeQuery("update \\Admin\\Models\\pm\\XhpmProject set iProductId = $productId where iProjectId in ({pIds:array})", ['pIds' => $pIds]);
                    if (!$re) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '审核失败');
                    }
                }
            }
            //项目成员表添加start
            if ($iProjectId) { //如果是编辑先把用户全部删除
                $projectmembers = XhpmProjectMember::find([
                    'conditions' => 'bDelete=0 AND iProjectId = :iProjectId: ',
                    'bind' => array('iProjectId' => $iProjectId),
                ]);
                foreach ($projectmembers as $projectmember) {
                    if ($projectmember->bIfOwner == 1) {
                        $ownerId = $projectmember->iUserId;
                    }
                    $projectmember->bDelete = 1;
                    $res = $projectmember->save();
                    if (!$res) {
                        $this->db->rollback();
                        return $iProjectId ? $this->sendErrorResponse(500, '编辑失败', '编辑成员失败')
                            : $this->sendErrorResponse(500, '创建失败', '添加成员失败');
                    }
                }
            }
            $projectMemberIds = $this->request->getPost('memberIds') ? $this->request->getPost('memberIds') : [];
            $ownerId = $ownerId ? $ownerId : $userId;
            array_push($projectMemberIds, $ownerId);
            $projectMemberIds = array_unique($projectMemberIds);
            foreach ($projectMemberIds as $projectMemberId) {
                //避免重复添加
                $member = XhpmProjectMember::findFirst([
                    'columns' => 'iId',
                    'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iProjectId = :iProjectId:',
                    'bind' => array('iUserId' => $projectMemberId, 'iProjectId' => $project->iProjectId),
                ]);
                if ($member) {//重复跳过
                    continue;
                }
                $projectMember = new XhpmProjectMember();
                $projectMember->iProjectId = $project->iProjectId;
                $projectMember->iUserId = $projectMemberId;
                if ($projectMemberId == $ownerId) {  //是否是创建者
                    $projectMember->bIfOwner = 1;
                }
                $re = $projectMember->save();
                if (!$re) {
                    $this->db->rollback();
                    return $iProjectId ? $this->sendErrorResponse(500, '编辑失败', '编辑成员失败')
                        :
                        $this->sendErrorResponse(500, '创建失败', '添加成员失败');
                }
            }
            //新增或者编辑版本成员父级联动修改
            if ($iProjectGrade == 2 && $iParentPid) {
                $members = XhpmProjectMember::find([
                    'columns' => 'iUserId',
                    'conditions' => 'bDelete=0 AND iProjectId = :iProjectId: ',
                    'bind' => array('iProjectId' => $iParentPid),
                ])->toArray();
                $uIds = array_column($members, iUserId);//项目原成员
                $newIds = array_values(array_diff($projectMemberIds, $uIds));
                foreach ($newIds as $newId) {
                    $member = new XhpmProjectMember();
                    $member->iUserId = $newId;
                    $member->iProjectId = $iParentPid;
                    $resu = $member->save();
                    if (!$resu) {
                        $this->db->rollback();
                        return $iProjectId ? $this->sendErrorResponse(500, '编辑失败')
                            :
                            $this->sendErrorResponse(500, '创建失败');
                    }
                }
            }
            //项目成员表添加end
            //写入项目日志
            $sContent = $iProjectId ? $userName . '编辑项目' . $project->sProjectName : $userName . '创建项目' . $project->sProjectName;
            $projectLog = new XhpmProjectLog();
            $projectLog->iProjectId = $project->iProjectId;
            $projectLog->sContent = $sContent;
            $r = $projectLog->save();
            if (!$r) {
                $this->db->rollback();
                return $iProjectId ? $this->sendErrorResponse(500, '编辑失败', '写入日志失败')
                    :
                    $this->sendErrorResponse(500, '创建失败', '写入日志失败');
            }
            //如果是新建项目则写入项目任务数统计表
            if (!$iProjectId) {
                $projectCount = new XhpmProjectCount();
                $projectCount->iProjectId = $project->iProjectId;
                $res = $projectCount->save();
                if (!$res) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '创建失败', '创建统计失败');
                }
            }
            $this->db->commit();
            return $iProjectId ? $this->sendSuccessResponse('编辑成功') : $this->sendSuccessResponse('创建成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iProjectId ?
                $this->sendErrorResponse(500, '编辑失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建失败', $exception->getMessage());
        }
    }

    /**
     * 获取已存在的老项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function getProjectInfoAction()
    {
        try {
            $iProjectId = $this->request->getPost('id', 'int');
            if (!$iProjectId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhpmProject::findFirst($iProjectId);
            $data = $obj ? $obj->toArray() : [];
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取项目信息失败', $exception->getMessage());
        }
    }

    /**
     * 开启/测试/发布/暂停/关闭项目/重启项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180413
     */
    public function changeStatusAction()
    {
        if (!Power::exist('Bpm_Project_ChangeStatus')) {
            return $this->sendErrorResponse('500', 权限不足);
        }
        $projectId = $this->request->getPost('iProjectId', 'int');
        $status = $this->request->getPost('iProjectStatus', 'int');
        if (!$projectId || !in_array($status, [2, 3, 4, 5, 6, 99])) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        $project = XhpmProject::findFirst([
            'conditions' => "iProjectId = $projectId AND bDelete =0",
        ]);
        if (empty($project)) {
            return $this->sendErrorResponse(400, '参数错误', '操作项目/版本不存在');
        }
        $pids = $this->getProjectIds();
        if ((!in_array($projectId, $pids)) && !User::isAdmin()) {
            return $this->sendErrorResponse(400, '参数错误', '无权操作该项目/版本');
        }
        //改变项目状态条件判定  版本 以及无版本的项目可变更状态
        $projectStatus = $project->iProjectStatus;
        if ($projectStatus == $status) {
            return $this->sendErrorResponse(500, '参数错误', '状态未变更');
        }
        $projectGrade = $project->iProjectGrade;
        if (!in_array($projectGrade, [1, 2])) {
            //非项目和版本不能变更状态
            return $this->sendErrorResponse(400, '参数错误', '模块不能变更状态');
        }
        if ($projectGrade == 1) {
            //项目下有版本变更状态
            $children = XhpmProject::findFirst([
                'conditions' => "iParentPid = $projectId AND bDelete = 0 AND iProjectGrade = 2",
            ]);
            if ($children) {
                return $this->sendErrorResponse(500, '请操作项目版本');
            }
        }
        $num = $this->getUnFinishTaskNum($projectId, $projectGrade);
        if ($num && in_array($projectStatus, [2, 3, 5]) && (!in_array($status, [2, 6, 99]))) {
            return $this->sendErrorResponse(500, '还有未完成的任务');
        }
        try {
            $this->db->begin(); //开启事务
            if ($project->iProjectStatus == 4) {//已完成
                return $this->sendErrorResponse(500, '项目/版本已发布');
            }
            if ($status == 99) {//重启
                if ($project->iProjectStatus != 6) {
                    return $this->sendErrorResponse(500, '项目状态错误', '项目非暂停状态');
                }
                $project->iProjectStatus = $project->iPauseStatus;
            } elseif ($status == 6) {//暂停
                $project->iPauseStatus = $projectStatus;
                $project->iProjectStatus = $status;
            } else {
                $project->iProjectStatus = $status;
            }
            $re = $project->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            //判断操作的是项目最新的版本
            if ($projectGrade == 2) {
                $parentId = $project->iParentPid;
                $visionObj = XhpmProject::findFirst([
                    'conditions' => "iParentPid = $parentId AND bDelete =0",
                    'order' => 'iProjectId DESC'
                ]);
                if ($visionObj) {
                    if ($visionObj->iProjectId == $projectId) {
                        $parenetObj = XhpmProject::findFirst([
                            'conditions' => "iProjectId = $parentId AND bDelete =0",
                        ]);
                        $parenetObj->iProjectStatus = $project->iProjectStatus;
                        $ret = $parenetObj->save();
                        if (!$ret) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '操作失败', '更改项目状态失败');
                        }
                    }
                }
            }
            $userName = Main::getLoginUserInfo('userName');
            $content = '';
            $step = '';
            $stateArr = '';
            switch ($status) {
                case 2:
                    $content = $userName . '开发项目' . $project->sProjectName;
                    $step = 40;
                    $stateArr = [40, 50, 99, 1];
                    break;
                case 3:
                    $content = $userName . '测试项目' . $project->sProjectName;
                    $step = 50;
                    $stateArr = [50, 99, 1];
                    break;
                case 4:
                    $content = $userName . '发布项目' . $project->sProjectName;
                    $step = 99;
                    $stateArr = [99, 1];
                    break;
                case 5:
                    $content = $userName . '完成项目' . $project->sProjectName;
                    $step = 1;
                    break;
                case 6:
                    $content = $userName . '暂停项目' . $project->sProjectName;
                    break;
                case 99:
                    $content = $userName . '重启项目' . $project->sProjectName;
                    break;
            }
            $projectLog = new XhpmProjectLog();
            $projectLog->iProjectId = $project->iProjectId;
            $projectLog->sContent = $content;
            $r = $projectLog->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败', '创建日志失败');
            }
            if (in_array($status, [2, 3, 4])) {//完成项目5暂时拿掉待后期扩展
                if ($projectGrade == 1) {
                    $iTTIds = XhpmProjectTask::find([
                        'columns' => 'iTTId',
                        'conditions' => "iProjectId=$projectId AND bDelete=0 AND iTTId >0",
                    ])->toArray();
                } elseif ($projectGrade == 2) {
                    $moudles = XhpmProject::find([
                        'conditions' => "iParentPid = $projectId AND bDelete =0 AND iProjectGrade = 3",
                    ])->toArray();
                    if ($moudles) {
                        $iTTIds = [];
                        foreach ($moudles as $moudle) {
                            $iIds = XhpmProjectTask::find([
                                'columns' => 'iTTId',
                                'conditions' => "iProjectId=$moudle[iProjectId] AND bDelete=0 AND iTTId >0",
                            ])->toArray();
                            $iTTIds = array_merge_recursive($iTTIds, $iIds);
                        }
                    } else {
                        $iTTIds = XhpmProjectTask::find([
                            'columns' => 'iTTId',
                            'conditions' => "iProjectId=$projectId AND bDelete=0 AND iTTId >0",
                        ])->toArray();
                    }
                }
                //如果有批量改导入的问题跟踪或者bug
                if ($iTTIds) {
                    foreach ($iTTIds as $iTTId) {
                        $trackObj = XhtrackTask::findFirst(
                            [
                                'conditions' => "iState NOT IN ({iStates:array}) and bDelete = 0 AND iTTId =$iTTId[iTTId]",
                                'bind' => ['iStates' => $stateArr]
                            ]
                        );
                        if ($trackObj) {
                            $trackObj->iState = $step;
                            $res = $trackObj->save();
                            if (!$res) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '操作失败', '关联问题跟踪或者Bug状态更改失败');
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 获取未完成数量
     *
     * @param $projectId
     * @param $projectGrade
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180802
     */
    private function getUnFinishTaskNum($projectId, $projectGrade)
    {
        $pids = [$projectId];
        if ($projectGrade == 1) {
            $vids = XhpmProject::find([
                'columns' => 'iProjectId',
                'conditions' => "iParentPid = $projectId AND bDelete = 0 AND iProjectGrade = 2"
            ])->toArray();
            $vids = array_column($vids, 'iProjectId');
            $mids = [];
            if (!empty($vids)) {
                $mids = XhpmProject::find([
                    'columns' => 'iProjectId',
                    'conditions' => 'bDelete = 0 AND iProjectGrade = 3 AND iParentPid IN ({vids:array})',
                    'bind' => ['vids' => $vids]
                ])->toArray();
                $mids = array_column($mids, 'iProjectId');
            }
            $pids = array_unique(array_merge($pids, $vids, $mids));
        } elseif ($projectGrade == 2) {
            $mids = XhpmProject::find([
                'columns' => 'iProjectId',
                'conditions' => "iParentPid = $projectId AND bDelete = 0 AND iProjectGrade = 3"
            ])->toArray();
            $mids = array_column($mids, 'iProjectId');
            $pids = array_unique(array_merge($pids, $mids));
        }
        $num = XhpmProjectTask::count([
            'columns' => 'iTaskId',
            'conditions' => 'bDelete = 0 AND (iTaskStatus = 1 OR iTaskStatus = 2) AND iProjectId IN ({pids:array})',
            'bind' => ['pids' => $pids]
        ]);
        return $num;
    }

    /**
     * 删除项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    public function delProjectByIdAction()
    {
        if (!Power::exist('Bpm_Project_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除权限');
        }
        $userName = Main::getLoginUserInfo('userName');
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        try {
            $projectObj = XhpmProject::findFirst([
                'conditions' => "bDelete = 0 AND iProjectId = $iProjectId"
            ]);
            if (!$projectObj) {
                return $this->sendErrorResponse(400, '参数错误', '删除目标不存在');
            }
            $pids = $this->getProjectIds();
            if ((!in_array($iProjectId, $pids)) && !User::isAdmin()) {
                return $this->sendErrorResponse(400, '参数错误', '无删除该项目权限');
            }
            $this->db->begin();
            $projectObj->bDelete = 1;
            $re = $projectObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            //删除子项目
            $result = $this->delChildrenProjects($iProjectId);
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除子级失败');
            }
            $grade = $projectObj->iProjectGrade;
            if ($grade == 1) {
                $content = $userName . '删除项目' . $projectObj->sProjectName;
            } elseif ($grade == 2) {
                $content = $userName . '删除版本' . $projectObj->sProjectVersion;
            } elseif ($grade == 3) {
                $content = $userName . '删除模块' . $projectObj->sProjectName;
            }
            $projectLog = new XhpmProjectLog();
            $projectLog->sContent = $content;
            $projectLog->iProjectId = $iProjectId;
            $res = $projectLog->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 删除子项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    private function delChildrenProjects($id)
    {
        $projects = XhpmProject::find([
            'conditions' => "bDelete = 0 AND iParentPid = $id"
        ]);
        foreach ($projects as $project) {
            $project->bDelete = 1;
            $re = $project->save();
            if (!$re) {
                return false;
            }
            $res = $this->delChildrenProjects($project->iProjectId);
            if (!$res) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取项目成员列表 form  and list
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180416
     * modify by zqk 20180508
     */
    public function getProjectMemberListAction()
    {
        $iProjectGrade = $this->request->getQuery('iProjectGrade', 'int');//项目等级
        $iParentPid = $this->request->getQuery('iParentPid', 'int');//项目父级ID
        if (in_array($iProjectGrade, [1, 2])) {
            if (User::isAdmin()) {
                $staffs = $this->modelsManager->createBuilder()
                    ->columns("s.iUserId,s.sStaffName,s.sPostName")
                    ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
                    ->leftjoin('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
                    ->where('s.bDelete = 0 and s.iStaffStatus = 1')
                    ->getQuery()
                    ->execute()
                    ->toArray();
            } else {
                $userInfo = Main::getLoginUserInfo();
                $deps = $userInfo['depId'];
                $deps = implode(",%' OR  sDepIds like '%,", $deps);
                $conditions = 's.bDelete = 0 and s.iStaffStatus = 1 and u.bDelete = 0 ';
                $conditions .= "AND (s.sDepIds like '%," . $deps . ",%' ) ";
                $staffs = $this->modelsManager->createBuilder()
                    ->columns("s.iUserId,s.sStaffName,s.sPostName")
                    ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
                    ->leftjoin('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
                    ->where($conditions)
                    ->getQuery()
                    ->execute()
                    ->toArray();
            }
        } elseif ($iProjectGrade == 3) {
            $params = array(
                'columns' => 'iUserId',
                'conditions' => "bDelete=:bDelete: AND iProjectId=:iProjectId: ",
                'bind' => array('iProjectId' => $iParentPid, 'bDelete' => 0),
            );
            $projectMember = new XhpmProjectMember();
            $members = $projectMember->find($params)->toArray();
            $inmems = [];//项目成员条件

            foreach ($members as $k => $member) {
                $inmems[] = $member['iUserId'];
            }
            $conditions = 's.bDelete = 0 and u.bDelete = 0  ';
            $staffs = $this->modelsManager->createBuilder()
                ->columns("s.iUserId,s.sStaffName,s.sPostName")
                ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
                ->leftjoin('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
                ->where($conditions)
                ->inWhere("s.iUserId", $inmems)
                ->getQuery()
                ->execute()
                ->toArray();
        }
        return $this->sendJsonResponse($staffs);
    }

    /**
     * 获取默认checked项目成员Ids
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180509
     */
    public function getCheckedMemberIdsAction()
    {
        $iProjectId = $this->request->getPost('iProjectId', 'int');//项目id
        $iProjectGrade = $this->request->getPost('iProjectGrade', 'int');//项目等级
        $iParentPid = $this->request->getPost('iParentPid', 'int');//项目父级ID
        $inmembers = [];
        //获取已选成员 新建版本默认已选项目成员   编辑默认已选本编辑项目成员
        if ($iProjectId) {//编辑成员
            $parameters = array(
                'columns' => 'iUserId',
                'conditions' => "bDelete=:bDelete: AND iProjectId=:iProjectId: ",
                'bind' => array('iProjectId' => $iProjectId, 'bDelete' => 0),
            );
            $projectMember = new XhpmProjectMember();
            $members = $projectMember->find($parameters)->toArray();
            foreach ($members as $k => $member) {
                $inmembers[] = $member['iUserId'];
            }
        } else {//新建
            if ($iProjectGrade == 2) {
                $parameters = array(
                    'columns' => 'iUserId',
                    'conditions' => "bDelete=:bDelete: AND iProjectId=:iProjectId: ",
                    'bind' => array('iProjectId' => $iParentPid, 'bDelete' => 0),
                );
                $projectMember = new XhpmProjectMember();
                $members = $projectMember->find($parameters)->toArray();
                foreach ($members as $k => $member) {
                    $inmembers[] = $member['iUserId'];
                }
            }
        }
        return $this->sendJsonResponse($inmembers);
    }

    /**
     * 获取项目树结构信息  id ,text easyui
     * @return string
     * created by zqk 2018/4/16
     */
    public function getProjectsAction()
    {
        $newArray[0]['id'] = 0;
        $newArray[0]['text'] = '学海教育';
        $newArray[0]['iconCls'] = 'fa fa-group';
        $newArray[0]['children'] = $this->getChildrenProject(0);
        return $this->sendJsonResponse($newArray);
    }

    /**
     * 获取子项目结构
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180409
     */

    private function getChildrenProject($iParentPid)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentPid=:iParentPid: ",
            'bind' => array('iParentPid' => $iParentPid, 'bDelete' => 0),
        );
        $objs = XhpmProject::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id'] = $value['iProjectId'];
            $newArray[$key]['text'] = $value['sProjectName'] ? $value['sProjectName'] : $value['sProjectVersion'];
            $newArray[$key]['iconCls'] = 'fa fa-group';
            $newArray[$key]['children'] = $this->getChildrenProject($value['iProjectId']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 根据项目id获取项目成员  tasklist 用到
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180419
     */
    public function getProjectMembersByIdAction()
    {
        $projectId = $this->request->getQuery('projectId', 'int');
        $members = $this->modelsManager->createBuilder()
            ->columns("m.iUserId,u.sStaffName")
            ->addFrom('Admin\Models\pm\XhpmProjectMember', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->where('m.bDelete = 0 AND m.iProjectId = :iProjectId:', array('iProjectId' => $projectId))
            ->getQuery()
            ->execute()
            ->toArray();
        $newArr = [];
        $newArr[0]['id'] = '';
        $newArr[0]['text'] = '选择执行人';
        foreach ($members as $k => $member) {
            $newArr[$k + 1]['id'] = $member['iUserId'];
            $newArr[$k + 1]['text'] = $member['sStaffName'];
        }
        return json_encode($newArr);
    }

    /**
     * 项目参数校验
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180521
     */
    private function checkProjectPower($grade, $iParentPid)
    {
        $visionPower = Power::exist('Bpm_Project_Version_Add');
        $moudlePower = Power::exist('Bpm_Project_Module_Add');
        if ($grade == 1) {
            if ($iParentPid == 0) {
                return true;
            } else {
                return false;
            }
        } elseif ($grade == 2) {
            if (!$visionPower) {
                return false;
            } elseif (!$iParentPid) {
                return false;
            }
            return true;
        } elseif ($grade == 3) {
            if (!$moudlePower) {
                return false;
            } elseif (!$iParentPid) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取列表相关员工
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180530
     */
    private function getProjectIds()
    {
        $deps = User::getextrapower('dep', 'project');  //获取扩展部门权限
        $uids = [];
        if ($deps) {
            $deps = implode(",%' OR  sDepIds like '%,", $deps);
            $conditions = 'bDelete = 0';
            $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
            $users = $this->modelsManager->createBuilder()
                ->columns("iUserId")
                ->From('Admin\Models\hrm\XhhrmStaff')
                ->where($conditions)
                ->getQuery()
                ->execute()
                ->toArray();
            foreach ($users as $k => $user) {
                $uids[] = $user['iUserId'];
            }
        }
        $userId = Main::getLoginUserInfo('userId');
        array_push($uids, $userId);
        $uids = array_unique($uids);
        $projectIds = $this->modelsManager->createBuilder()
            ->columns("iProjectId")
            ->addFrom('Admin\Models\pm\XhpmProjectMember')
            ->where("bDelete = 0")
            ->inwhere('iUserId', $uids)
            ->groupBy('iProjectId')
            ->getQuery()
            ->execute()
            ->toArray();
        $pids = array_column($projectIds, 'iProjectId');
        return $pids;
    }

    /**
     * 获取应用列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180516
     * modify by zqk 20180627
     */
    public function getProductsAction()
    {
        try {
            $apps = XhpmProduct::find([
                'columns' => 'iId,sName,iType',
                'conditions' => 'bDelete = 0',
            ])->toArray();
            $data = [];
            $productTypes = self::$productTypes;
            foreach ($apps as $k => $app) {
                $data[$k]['id'] = $app['iId'];
                $data[$k]['text'] = $app['sName'] . '(' . $productTypes[$app['iType']] . ')';
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取应用失败', $exception->getMessage());
        }
    }

    /**
     * 审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180724
     */
    public function checkProjectByIdAction()
    {
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        $userName = Main::getLoginUserInfo('userName');
        try {
            $this->db->begin();  //开启事务
            if (!Power::exist('Bpm_Project_Check')) {
                return $this->sendErrorResponse(400, '权限不足', '无审核权限');
            }
            if (!$iProjectId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $project = XhpmProject::findFirst([
                'conditions' => "iProjectId = $iProjectId AND bDelete = 0"
            ]);
            if (!$project) {
                return $this->sendErrorResponse(400, '审核失败', '审核项目/版本/模块不存在');
            }
            $grade = $project->iProjectGrade;
            $pIds = $this->getPids($iProjectId, $grade);
            $taskIds = $this->modelsManager->createBuilder()
                ->columns("iTaskId")
                ->addFrom('Admin\Models\pm\XhpmProjectTask')
                ->where('bDelete = 0 AND bChecked = 0')
                ->inwhere('iProjectId', $pIds)
                ->getQuery()
                ->execute()
                ->toArray();
            $taskIds = array_column($taskIds, 'iTaskId');
            if (!$taskIds) {
                return $this->sendErrorResponse(400, '审核失败', '没有要审核的相关任务');
            }
            $re = $this->modelsManager->executeQuery("update \\Admin\\Models\\pm\\XhpmProject set bChecked = 1 where iProjectId in ({pIds:array})", ['pIds' => $pIds]);
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '审核失败');
            }
            $res = $this->modelsManager->executeQuery("update \\Admin\\Models\\pm\\XhpmProjectTask set bChecked = 1 where iTaskId in ({taskIds:array})", ['taskIds' => $taskIds]);
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '审核失败');
            }
            $content = $userName . '审核项目' . $project->sProjectName;
            $projectLog = new XhpmProjectLog();
            $projectLog->sContent = $content;
            $projectLog->iProjectId = $iProjectId;
            $result = $projectLog->save();
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '审核失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('审核成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     * 获取需要操作项目Ids
     *
     * @param $pid
     * @param $grade
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180724
     */
    private function getPids($pid, $grade)
    {
        $vIds = [];
        $mIds = [];
        if ($grade == 1) {
            $vIds = XhpmProject::find([
                'columns' => 'iProjectId',
                'conditions' => "iParentPid = $pid AND bDelete = 0"
            ])->toArray();
            $vIds = array_column($vIds, 'iProjectId');
            if ($vIds) {
                $mIds = $this->modelsManager->createBuilder()
                    ->columns("iProjectId")
                    ->addFrom('Admin\Models\pm\XhpmProject')
                    ->where('bDelete = 0')
                    ->inwhere('iParentPid', $vIds)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $mIds = array_column($mIds, 'iProjectId');
            }
        } elseif ($grade == 2) {
            $mIds = XhpmProject::find([
                'columns' => 'iProjectId',
                'conditions' => "iParentPid = $pid AND bDelete = 0"
            ])->toArray();
            $mIds = array_column($mIds, 'iProjectId');
        }
        $pIds = array_merge([$pid], $vIds, $mIds);
        return $pIds;
    }

    /* ***********************************逻辑分离代码需要补充*********************************************/
    /**
     * 归档项目
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    public function archiveProjectByIdAction()
    {
        if (!Power::exist('Bpm_Project_Archive')) {
            return $this->sendErrorResponse(500, '权限不足', '无归档权限');
        }
        $userName = Main::getLoginUserInfo('userName');
        $iProjectId = $this->request->getPost('iProjectId', 'int');
        try {
            $this->db->begin();
            $pIds = $this->getProjectIds();
            if (!in_array($iProjectId, $pIds)) {
                return $this->sendErrorResponse(400, '参数错误', '无操作该项目权限');
            }
            $projectObj = XhpmProject::findFirst([
                'conditions' => "bDelete = 0 AND iProjectId = $iProjectId"
            ]);
            if (empty($projectObj)) {
                return $this->sendErrorResponse(400, '参数错误', '该项目不存在');
            }
            if ($projectObj->bArchived == 1) {
                return $this->sendErrorResponse(400, '项目已归档');
            }
            if ($projectObj->iProjectGrade != 1) {
                return $this->sendErrorResponse(400, '请操作项目');
            }
            $cIds = $this->getPids($iProjectId, 1);
            if ($cIds) {
                $re = $this->modelsManager->executeQuery("update \\Admin\\Models\\pm\\XhpmProject set bArchived = 1 where iProjectId in ({pIds:array})", ['pIds' => $cIds]);
                if (!$re) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '操作失败');
                }
            }
            $content = $userName . '归档项目' . $projectObj->sProjectName;
            $projectLog = new XhpmProjectLog();
            $projectLog->sContent = $content;
            $projectLog->iProjectId = $iProjectId;
            $res = $projectLog->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }
}

